package com.maoshi.shop.security.api.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.maoshi.shop.security.api.model.MaoshiUser;
import com.maoshi.shop.security.api.service.AppLoginService;
import com.maoshi.shop.security.api.service.MaoshiUserDetailsService;
import com.maoshi.shop.security.comment.enums.App;
import com.maoshi.shop.security.comment.exception.WxErrorException;
import com.maoshi.shop.security.comment.model.AppConnect;
import com.maoshi.shop.security.comment.service.AppConnectService;
import com.maoshi.shop.security.comment.token.AuthenticationToken;
import lombok.AllArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;


/**
 * 小程序登陆
 * @author LGH
 */
@Component
@AllArgsConstructor
public class MaAppLoginServiceImpl implements AppLoginService {

    private final MaoshiUserDetailsService maoshiUserDetailsService;

    private final WxMaService wxMaService;

    private final AppConnectService appConnectService;

    @Override
    public UserDetails loginAndGetUserDetails(AuthenticationToken authentication) {
        String code = authentication.getPrincipal();
        try {

            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
            AppConnect appConnect = appConnectService.getByBizUserId(session.getOpenid(), authentication.getAppType());

            //合并代码开始
            //AppConnect appConnect1 = appConnectService.getByBizUserId(session.getUnionid(), authentication.getAppType());

            //if (appConnect1==null && appConnect == null) {
            if (appConnect == null) {
            //合并代码结束
                appConnect = new AppConnect();
                appConnect.setAppId(authentication.getAppType());
                appConnect.setBizUserId(session.getOpenid());
                appConnect.setBizUnionid(session.getUnionid());
                appConnectService.save(appConnect);
            }
            MaoshiUser maoshiUser = maoshiUserDetailsService.loadUserByAppConnect(appConnect);
            maoshiUser.setSessionKey(session.getSessionKey());
            return maoshiUser;
        } catch (me.chanjar.weixin.common.error.WxErrorException e) {
            throw new WxErrorException(e.getMessage());
        }
    }

    @Override
    public App getApp() {
        return App.MINI;
    }


}
